package java_IO;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 例子参考：http://www.cnblogs.com/skywang12345/p/io_03.html
 */
public class demo_02_ByteArrayOutputStream {
    public static void main(String[] arge) throws IOException {
        // 依次写入“A”、“B”、“C”三个字母
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byteArrayOutputStream.write('A');
        byteArrayOutputStream.write('B');
        byteArrayOutputStream.write('C');
        System.out.printf("baos=%s\n", byteArrayOutputStream.toString());

        // 将ArrayLetters数组中从“3”开始的后5个字节写入到baos中。
        byteArrayOutputStream.write("ABCDEFJHIGKLMN".getBytes(), 3, 5);
        byteArrayOutputStream.write("123".getBytes());
        System.out.printf("baos=%s\n", byteArrayOutputStream);

        // 计算长度
        int size = byteArrayOutputStream.size();
        System.out.printf("size=%s\n", size);

        // 转换成byte[]数组
        byte[] buf = byteArrayOutputStream.toByteArray();
        String str = new String(buf);
        System.out.printf("str=%s\n", str);

        // 将baos写入到另一个输出流中
        try {
            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
            byteArrayOutputStream.writeTo((OutputStream)baos2);
            System.out.printf("baos2=%s\n", baos2);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
